package org.darcy.service.impl;

import java.util.Date;

import org.darcy.dao.SysRoleResourcesMapper;
import org.darcy.entity.SysRoleResources;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.service.SysRoleResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 角色资源
 */
@Service
public class SysRoleResourcesServiceImpl extends GenericServiceImpl<SysRoleResources>
		implements SysRoleResourcesService {

	@Autowired
	private SysRoleResourcesMapper resourceMapper;



	/**
	 * 添加角色资源
	 * 
	 * @param roleId
	 * @param resourcesId
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void addRoleResources(Long roleId, String resourcesId) {
		// 删除
		removeByRoleId(roleId);
		// 添加
		if (!StringUtils.isEmpty(resourcesId)) {
			String[] resourcesArr = resourcesId.split(",");
			SysRoleResources r = null;
			for (String ri : resourcesArr) {
				r = new SysRoleResources();
				r.setRoleId(roleId);
				r.setResourcesId(Long.parseLong(ri));
				r.setCreateTime(new Date());
				r.setUpdateTime(new Date());
				resourceMapper.insert(r);
			}

		}
	}

	/**
	 * 通过角色id批量删除
	 * 
	 * @param roleId
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void removeByRoleId(Long roleId) {
		// 删除
		QueryWrapper<SysRoleResources> q = new QueryWrapper<SysRoleResources>();
		q.eq("role_id", roleId);
		resourceMapper.delete(q);
	}
}
